/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import java.sql.*;

/**
 *
 * @author Milleo
 */
public class Database {
    
    static final String HOST = "localhost";
    static final String PORT = "3306";
    static final String DATABASE = "Gerenciador_Projetos";
    static final String USER = "root";
    static final String PASSWORD = "123";
    private Connection connection;
    private Statement stmt;
    public ResultSet res;
    
    public void connect(){
        String url =  "jdbc:mysql://" + HOST  + ":" + PORT + "/" + DATABASE;
        try{            
            this.connection = DriverManager.getConnection(url, USER, PASSWORD);
            this.stmt = this.connection.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    public void disconnect(){
        try{
            this.connection.close();        
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void query(String sqlCommand){
        try{
            this.res = this.stmt.executeQuery(sqlCommand);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public int executeUpdate(String sqlCommand){
        try{
            int affectedRows = this.stmt.executeUpdate(sqlCommand, this.stmt.RETURN_GENERATED_KEYS);
            if (affectedRows == 0)
                throw new SQLException("Creating user failed, no rows affected.");
            
            ResultSet generatedKeys = this.stmt.getGeneratedKeys();
            if (generatedKeys.next()) {
                return generatedKeys.getInt(1);
            } else {
                throw new SQLException("Creating user failed, no generated key obtained.");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
        return 0;
    }
}
